import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:edu/constants/config.dart';
import 'package:edu/networks/account/models/user_response.dart';
import 'package:edu/utils/app_preferences.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:edu/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart'
    as cache_manager;

class AccountInfo {
  static const _kEduSecondsKey = 'edu_seconds';
  // 用户信息-APP 的消息通知模块（仅推送关键事件摘要，而非完整内容）、
  // 后台系统向用户推送的简洁状态提醒
  //（如 “任务已完成”“订单更新” 等短通知），
  // 或是工具类产品中定向给用户发送的简要信息提示组件
  final userBriefNotifier = ValueNotifier<UserBrief?>(null);
  // 用户信息-用于保障用户或系统对资料动态的感知
  final userProfileNotifier = ValueNotifier<UserProfile?>(null);
  final avatarChangeIndexNotifier = ValueNotifier<int>(0);
  final eduSecondsNotifier = ValueNotifier<int?>(null);

  bool get isLoggedIn => userBriefNotifier.value != null;
  UserBrief? get userBrief => userBriefNotifier.value;
  UserProfile? get userProfile => userProfileNotifier.value;

  int? get accountId => userBriefNotifier.value?.id;

  // 课程存在购物车中
  List<int> get purchasingCourses =>
      userBriefNotifier.value?.purchasingCourses ?? [];
  // 购买的课程
  List<int> get purchasedCourses =>
      userBriefNotifier.value?.purchasedCourses ?? [];

  AccountInfo._();
  static final shared = AccountInfo._();

  Future<void> init() async {
    _loadUserBrief();
  }

  /* 登录 */
  Future<void> login(UserBrief userBrief, String token) async {
    // 保存 token
    AppPreferences.shared.userToken = token;
    // 更新请求授权令牌
    DataFetcher.shared.updateAuthorizationToken(token);

    _setUserBrief(userBrief);
  }

  /* 登出 */
  Future<void> logout() async {
    // 删除 token
    AppPreferences.shared.userToken = null;
    // 删除请求授权令牌
    DataFetcher.shared.updateAuthorizationToken(null);

    // 删除用户信息
    userBriefNotifier.value = null;
    userProfileNotifier.value = null;
    // 重置头像索引
    avatarChangeIndexNotifier.value = 0;

    // 删除用户头像缓存
    const url = '${Config.baseUrl}/v1/user/avatar';
    PaintingBinding.instance.imageCache.evict(
      const CachedNetworkImageProvider(url),
    );
    await cache_manager.DefaultCacheManager().removeFile(url);
  }

  /* 更新用户信息 */
  void updateUserProfile(UserProfile userProfile) {
    userProfileNotifier.value = userProfile;
    final brief = userProfile.getUserBrief();
    if (userBriefNotifier.value != brief) {
      userBriefNotifier.value = brief;
    }
    avatarChangeIndexNotifier.value++;
  }

  /* 更新头像 */
  void updateAvatar(String? avatar) async {
    // 清除缓存
    const url = '${Config.baseUrl}/v1/user/avatar';
    PaintingBinding.instance.imageCache.evict(
      const CachedNetworkImageProvider(url),
    );
    // 删除缓存
    await cache_manager.DefaultCacheManager().removeFile(url);

    final newBrief = userBrief?.copyWith(avatar: avatar);
    userBriefNotifier.value = newBrief;

    final newProfile = userProfile?.copyWith(avatar: avatar);
    userProfileNotifier.value = newProfile;

    avatarChangeIndexNotifier.value++;
  }

  /* 更新用户昵称 */
  void updateNickname(String? nickname) {
    final newBrief = userBriefNotifier.value?.copyWith(name: nickname);
    userBriefNotifier.value = newBrief;

    final newProfile = userProfileNotifier.value?.copyWith(name: nickname);
    userProfileNotifier.value = newProfile;
  }

  /* 更新用户职业 */
  void updateProfession(String? profession) {
    final newProfile = userProfileNotifier.value?.copyWith(
      profession: profession,
    );
    userProfileNotifier.value = newProfile;
  }

  /* 更新用户性别 */
  void updateGender(String? gender) {
    final newBrief = userBriefNotifier.value?.copyWith(gender: gender);
    userBriefNotifier.value = newBrief;

    final newProfile = userProfileNotifier.value?.copyWith(gender: gender);
    userProfileNotifier.value = newProfile;
  }

  /* 更新用户地区或地址 */
  void updateRegion(String? region, List<String>? regionCodeList) {
    final newProfile = userProfileNotifier.value?.copyWith(
      region: region,
      regionCodeList: regionCodeList,
    );
    userProfileNotifier.value = newProfile;
  }

  /* 更新用户签名 */
  void updateIntroduction(String? introduction) {
    final newProfile = userProfileNotifier.value?.copyWith(
      introduction: introduction,
    );
    userProfileNotifier.value = newProfile;
  }

  /* 邮箱 */
  void updateEmail(String? email) {
    final newProfile = userProfileNotifier.value?.copyWith(email: email);
    userProfileNotifier.value = newProfile;
  }

  /* 手机号 */
  void updatePhoneNumber(String? phoneNumber) {
    final newProfile = userProfileNotifier.value?.copyWith(
      phoneNumber: phoneNumber,
    );
    userProfileNotifier.value = newProfile;
  }

  /* 添加学习时长 */
  Future<void> addEduTimeInSeconds(int seconds) async {
    final current = eduSecondsNotifier.value ?? 0;
    eduSecondsNotifier.value = current + seconds;

    await DatabaseHelper.shared.setKeyValue(
      _kEduSecondsKey,
      integer: current + seconds,
    );
  }

  /* 用于实现 Flutter 中的状态管理，当它们的值发生变化时，监听它们的 UI 组件会自动刷新 */
  void _setUserBrief(UserBrief? userBrief) async {
    userBriefNotifier.value = userBrief;
    avatarChangeIndexNotifier.value++;

    eduSecondsNotifier.value =
        await DatabaseHelper.shared.getIntegerValue(_kEduSecondsKey) ?? 0;
  }

  // 加载用户信息
  void _loadUserBrief() async {
    if (AppPreferences.shared.userToken == null) {
    } else {
      try {
        final response = await DataFetcher.shared.userApi.getUserBrief();
        if (response.code == 0) {
          _setUserBrief(response.brief);
        }
      } catch (e) {
        log('获取用户信息失败: ${e.toString()}');
      }
    }
  }

  // 添加课程到购物车
  void addCourseToShoppingCarts(int courseId) {
    if (purchasedCourses.contains(courseId)) {
      return;
    }

    // 防止重复添加到购物车
    if (purchasingCourses.contains(courseId)) {
      return;
    }

    final purchasings = userBriefNotifier.value?.purchasingCourses ?? [];
    final newBrief = userBriefNotifier.value?.copyWith(
      purchasingCourses: [...purchasings, courseId],
    );
    userBriefNotifier.value = newBrief;

    final newProfile = userProfileNotifier.value?.copyWith(
      purchasingCourses: [...purchasings, courseId],
    );
    userProfileNotifier.value = newProfile;
  }

  // 课程购买
  void coursePurchased(List<int> courseIds) {
    final purchasings = userBriefNotifier.value?.purchasingCourses ?? [];
    final newPurchasings = purchasings
        .where((element) => !courseIds.contains(element))
        .toList();
    final newBrief = userBriefNotifier.value?.copyWith(
      purchasingCourses: newPurchasings,
      purchasedCourses: [...purchasedCourses, ...courseIds],
    );
    userBriefNotifier.value = newBrief;

    final newProfile = userProfileNotifier.value?.copyWith(
      purchasingCourses: newPurchasings,
      purchasedCourses: [...purchasedCourses, ...courseIds],
    );
    userProfileNotifier.value = newProfile;
  }

  // 删除购物车中的课程
  void removeCourseFromShoppingCarts(List<int> courseIds) {
    final purchasings = userBriefNotifier.value?.purchasingCourses ?? [];
    final newPurchasings = purchasings
        .where((element) => !courseIds.contains(element))
        .toList();
    final newBrief = userBriefNotifier.value?.copyWith(
      purchasingCourses: newPurchasings,
    );
    userBriefNotifier.value = newBrief;

    final newProfile = userProfileNotifier.value?.copyWith(
      purchasingCourses: newPurchasings,
    );
    userProfileNotifier.value = newProfile;
  }
}
